module.exports = app => {
    const express = require('express')
    const router = express.Router()
    const AdminUser = require(`../../models/AdminUser`)
    const jwt = require('jsonwebtoken')
    const assert = require('http-assert')

    router.post('/', async (req, res) => {
        const model = await req.model.create(req.body)
        res.send(model)
    })

    router.get('/', async (req, res) => {
        let queryOtions = {}
        let findAnd = {}
        let opts = {
            path: 'categories',
            select: 'name',
        }
        if (req.model.modelName === 'Category') {
            queryOtions.populate = 'parent';
            // findAnd = { parent: { $ne: null } } 
        } else {
            queryOtions.populate = '';
            // findAnd = {}
        }
        req.model.modelName === 'Hero' ? queryOtions.populate = opts : ''
        let list = await req.model.find(findAnd).setOptions(queryOtions)

        res.send(list)
    })

    router.get('/:id', async (req, res) => {
        const model = await req.model.findById(req.params.id)
        res.send(model)
    })

    router.post('/edit', async (req, res) => {
        const model = await req.model.findByIdAndUpdate(req.body.id, req.body)
        res.send(model)
    })

    router.post('/delete', async (req, res) => {
        let model = await req.model.findByIdAndDelete(req.body.id, req.body)
        res.send({
            success: true,
            result: model
        })
    })

    const authMiddleware = require('../../middleware/auth')
    const resourceMiddleware = require('../../middleware/resource')
    app.use('/admin/api/common/:resource', authMiddleware(), resourceMiddleware(), router)

    const multer = require('multer')
    const upload = multer({ dest: __dirname + '/../../uploads' })
    app.post('/admin/api/upload', authMiddleware(), upload.single('file'), (req, res) => {
        let file = req.file
        file.url = `http://localhost:3030/uploads/${file.filename}`
        res.send(file)
    })

    app.post('/admin/api/login', async (req, res) => {
        const { username, password } = req.body
        // 查找数据
        let model = await AdminUser.findOne({ username }).select('+password')
        // console.log(model)
        // 校验密码
        let isValid = require('bcrypt').compareSync(password, model.password)
        // console.log(isValid)
        if (!model || !isValid) {
            return res.status(422).send({
                message: '用户名或密码不正确'
            })
        }
        // 发送token
        let token = jwt.sign({ id: model._id }, app.get('secret'))
        res.send({ token })
    })

    app.use(async (err, req, res, next) => {
        res.status(err.statusCode||500).send({
            message: err.message
        })
    })
}